<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog large-dialog" @click.stop>
      <div class="apple-card__header">
        <div class="header-content">
          <h2 class="text-heading">权限管理</h2>
          <p class="text-caption">{{ role?.name }} ({{ role?.code }})</p>
        </div>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <div class="apple-card__body">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p class="text-body">加载权限数据...</p>
        </div>

        <!-- 权限内容 -->
        <div v-else class="permissions-content">
          <!-- 搜索和筛选 -->
          <div class="permission-toolbar">
            <div class="search-group">
              <input
                v-model="searchQuery"
                class="apple-input"
                placeholder="搜索权限..."
              >
            </div>
            <div class="filter-group">
              <select v-model="selectedModule" class="apple-input">
                <option value="">所有模块</option>
                <option v-for="module in modules" :key="module" :value="module">
                  {{ getModuleName(module) }}
                </option>
              </select>
            </div>
            <div class="action-group">
              <button 
                class="apple-button apple-button--secondary"
                @click="selectAllVisible"
              >
                全选可见
              </button>
              <button 
                class="apple-button apple-button--secondary"
                @click="clearAllVisible"
              >
                清空可见
              </button>
            </div>
          </div>

          <!-- 权限列表 -->
          <div class="permissions-list">
            <div v-if="filteredPermissions.length === 0" class="empty-permissions">
              <div class="empty-icon">🔐</div>
              <p class="text-body">未找到匹配的权限</p>
            </div>

            <div v-else class="permissions-modules">
              <div 
                v-for="[module, modulePermissions] in groupedPermissions" 
                :key="module"
                class="permission-module"
              >
                <div class="module-header">
                  <div class="module-info">
                    <h3 class="text-subheading">{{ getModuleName(module) }}</h3>
                    <span class="text-caption">{{ modulePermissions.length }} 个权限</span>
                  </div>
                  <div class="module-actions">
                    <button 
                      class="apple-button apple-button--text apple-button--small"
                      @click="toggleModulePermissions(module, modulePermissions)"
                    >
                      {{ isModuleAllSelected(module, modulePermissions) ? '取消全选' : '全选' }}
                    </button>
                  </div>
                </div>

                <div class="permissions-grid">
                  <div 
                    v-for="permission in modulePermissions" 
                    :key="permission.id"
                    class="permission-item"
                    :class="{ 'permission-item--selected': isPermissionSelected(permission.id) }"
                    @click="togglePermission(permission.id)"
                  >
                    <div class="permission-info">
                      <div class="permission-header">
                        <span class="permission-name">{{ permission.name }}</span>
                        <span 
                          class="apple-tag"
                          :class="getActionTagClass(permission.action)"
                        >
                          {{ permission.action }}
                        </span>
                      </div>
                      <p class="permission-description">
                        {{ permission.description || '暂无描述' }}
                      </p>
                      <div class="permission-meta">
                        <span class="text-caption">{{ permission.code }}</span>
                      </div>
                    </div>
                    <div class="permission-checkbox">
                      <div 
                        class="apple-switch apple-switch--small"
                        :class="{ 'apple-switch--active': isPermissionSelected(permission.id) }"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="apple-card__footer">
        <div class="permission-summary">
          <span class="text-caption">
            已选择 {{ selectedPermissions.size }} / {{ allPermissions.length }} 个权限
          </span>
        </div>
        <div class="footer-actions">
          <button 
            type="button"
            class="apple-button apple-button--secondary"
            @click="handleClose"
          >
            取消
          </button>
          <button 
            type="button"
            class="apple-button apple-button--primary"
            :disabled="submitting || !hasChanges"
            @click="handleSave"
          >
            {{ submitting ? '保存中...' : '保存权限' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { rbacApi } from '@/api/rbac'
import type { Role, Permission } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
  role: Role | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态
const loading = ref(false)
const submitting = ref(false)
const allPermissions = ref<Permission[]>([])
const selectedPermissions = ref<Set<number>>(new Set())
const originalPermissions = ref<Set<number>>(new Set())

// 搜索和筛选
const searchQuery = ref('')
const selectedModule = ref('')

// 模块名称映射
const moduleNames = {
  dashboard: '仪表盘',
  customers: '客户管理',
  activities: '活动管理',
  products: '产品管理',
  opportunities: '销售机会',
  tours: '出团管理',
  aftercare: '售后服务',
  statistics: '统计分析',
  system: '系统管理'
}

// 计算属性
const modules = computed(() => {
  const moduleSet = new Set(allPermissions.value.map(p => p.resource.module))
  return Array.from(moduleSet).sort()
})

const filteredPermissions = computed(() => {
  let filtered = allPermissions.value

  // 模块筛选
  if (selectedModule.value) {
    filtered = filtered.filter(p => p.resource.module === selectedModule.value)
  }

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(p => 
      p.name.toLowerCase().includes(query) ||
      p.code.toLowerCase().includes(query) ||
      p.description?.toLowerCase().includes(query)
    )
  }

  return filtered
})

const groupedPermissions = computed(() => {
  const groups = new Map<string, Permission[]>()
  
  filteredPermissions.value.forEach(permission => {
    const module = permission.resource.module
    if (!groups.has(module)) {
      groups.set(module, [])
    }
    groups.get(module)!.push(permission)
  })

  // 按模块排序
  const sortedGroups = new Map()
  Array.from(groups.keys()).sort().forEach(key => {
    sortedGroups.set(key, groups.get(key))
  })

  return sortedGroups
})

const hasChanges = computed(() => {
  if (selectedPermissions.value.size !== originalPermissions.value.size) {
    return true
  }
  
  for (const id of selectedPermissions.value) {
    if (!originalPermissions.value.has(id)) {
      return true
    }
  }
  
  return false
})

// 工具函数
const getModuleName = (module: string) => {
  return moduleNames[module as keyof typeof moduleNames] || module
}

const getActionTagClass = (action: string) => {
  const classes = {
    'read': 'apple-tag--primary',
    'create': 'apple-tag--success', 
    'update': 'apple-tag--warning',
    'delete': 'apple-tag--danger'
  }
  return classes[action as keyof typeof classes] || 'apple-tag'
}

// 权限操作函数
const isPermissionSelected = (permissionId: number) => {
  return selectedPermissions.value.has(permissionId)
}

const togglePermission = (permissionId: number) => {
  if (selectedPermissions.value.has(permissionId)) {
    selectedPermissions.value.delete(permissionId)
  } else {
    selectedPermissions.value.add(permissionId)
  }
}

const isModuleAllSelected = (module: string, modulePermissions: Permission[]) => {
  return modulePermissions.every(p => selectedPermissions.value.has(p.id))
}

const toggleModulePermissions = (module: string, modulePermissions: Permission[]) => {
  const allSelected = isModuleAllSelected(module, modulePermissions)
  
  if (allSelected) {
    // 取消全选
    modulePermissions.forEach(p => selectedPermissions.value.delete(p.id))
  } else {
    // 全选
    modulePermissions.forEach(p => selectedPermissions.value.add(p.id))
  }
}

const selectAllVisible = () => {
  filteredPermissions.value.forEach(p => selectedPermissions.value.add(p.id))
}

const clearAllVisible = () => {
  filteredPermissions.value.forEach(p => selectedPermissions.value.delete(p.id))
}

// 数据加载
const loadPermissions = async () => {
  loading.value = true
  try {
    const response = await rbacApi.getPermissions()
    if (response.success) {
      allPermissions.value = response.data
    }
  } catch (error) {
    console.error('加载权限列表失败:', error)
    ElMessage.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const loadRolePermissions = async () => {
  if (!props.role) return
  
  try {
    // TODO: 获取角色当前权限
    // const response = await rbacApi.getRolePermissions(props.role.id)
    // if (response.success) {
    //   const permissionIds = response.data.map(p => p.id)
    //   selectedPermissions.value = new Set(permissionIds)
    //   originalPermissions.value = new Set(permissionIds)
    // }
  } catch (error) {
    console.error('加载角色权限失败:', error)
  }
}

// 保存权限
const handleSave = async () => {
  if (!props.role || !hasChanges.value) return
  
  submitting.value = true
  
  try {
    const permissionIds = Array.from(selectedPermissions.value)
    const response = await rbacApi.assignPermissionsToRole(props.role.id, {
      role_id: props.role.id,
      permission_ids: permissionIds
    })
    
    if (response.success) {
      originalPermissions.value = new Set(selectedPermissions.value)
      emit('updated')
      handleClose()
      ElMessage.success('权限保存成功')
    }
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 重置状态
const resetState = () => {
  searchQuery.value = ''
  selectedModule.value = ''
  selectedPermissions.value.clear()
  originalPermissions.value.clear()
}

// 监听对话框打开
watch([() => props.modelValue, () => props.role], async ([newValue, newRole]) => {
  if (newValue && newRole) {
    resetState()
    await loadPermissions()
    await loadRolePermissions()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.large-dialog {
  width: 100%;
  max-width: 900px;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  flex: 1;
}

.header-content .text-caption {
  margin-top: var(--spacing-xs);
  color: var(--text-secondary);
}

.close-button {
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.apple-card__body {
  max-height: 60vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--apple-gray-5);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.permissions-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.permission-toolbar {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  align-items: center;
  flex-wrap: wrap;
}

.search-group {
  flex: 1;
  min-width: 200px;
}

.filter-group {
  min-width: 150px;
}

.action-group {
  display: flex;
  gap: var(--spacing-sm);
}

.permissions-list {
  flex: 1;
  overflow-y: auto;
  padding-right: var(--spacing-xs);
}

.empty-permissions {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: var(--spacing-md);
  opacity: 0.5;
}

.permission-module {
  margin-bottom: var(--spacing-xl);
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
  padding-bottom: var(--spacing-sm);
  border-bottom: 2px solid var(--border-primary);
}

.module-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: var(--spacing-md);
}

.permission-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-medium);
  cursor: pointer;
  transition: all var(--duration-fast) var(--ease-out);
}

.permission-item:hover {
  border-color: var(--color-primary);
  background-color: var(--bg-secondary);
}

.permission-item--selected {
  border-color: var(--color-primary);
  background-color: rgba(0, 122, 255, 0.05);
}

.permission-info {
  flex: 1;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-xs);
}

.permission-name {
  font-weight: 500;
  color: var(--text-primary);
}

.permission-description {
  font-size: 12px;
  color: var(--text-secondary);
  margin: var(--spacing-xs) 0;
  line-height: 1.4;
}

.permission-meta {
  font-family: 'SF Mono', Monaco, monospace;
  font-size: 11px;
  color: var(--text-tertiary);
}

.permission-checkbox {
  margin-left: var(--spacing-md);
}

.apple-switch--small {
  width: 32px;
  height: 18px;
  border-radius: 9px;
}

.apple-switch--small::before {
  width: 14px;
  height: 14px;
  top: 2px;
  left: 2px;
}

.apple-switch--small.apple-switch--active::before {
  transform: translateX(14px);
}

.apple-card__footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-summary {
  color: var(--text-secondary);
}

.footer-actions {
  display: flex;
  gap: var(--spacing-sm);
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .large-dialog {
    max-height: 95vh;
  }
  
  .permission-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-group,
  .filter-group {
    min-width: auto;
  }
  
  .permissions-grid {
    grid-template-columns: 1fr;
  }
  
  .apple-card__footer {
    flex-direction: column;
    gap: var(--spacing-md);
  }
  
  .footer-actions {
    width: 100%;
    justify-content: stretch;
  }
  
  .footer-actions .apple-button {
    flex: 1;
  }
}
</style>